package com.dragon.blelibrary.bleutils;

import android.content.Context;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.Bitmap.CompressFormat;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.net.Uri;
import android.os.Environment;


import com.dragon.blelibrary.BleConfig;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

class FileUtils
{

   private static String mPath	= Environment.getExternalStorageDirectory() + File.separator + BleConfig.rootFile;
   public static final String CAMERA_IMAGE_PATH = "DCIM/Camera/";
   public static String PHOTO_PATH = mPath + CAMERA_IMAGE_PATH;
   /**手环固件文件名*/
   public static String banName = "Musering.zip";
   /**下载后的APP文件名*/
   public static String appName = "Musering.apk";

   /**
    * 判断指定路径文件是否存在，如果不存在直接生成一个新的文件
    * @param path ： 文件指定路径
    */
   public static void isExist(String path)
   {
       File file = new File(path);
       // 判断文件夹是否存在,如果不存在则创建文件夹
       if (!file.exists())
       {
           synchronized (FileUtils.class)
           {
               file.mkdirs();
           }
       }
   }

   public static boolean isFileExist(String path)
   {
       File file = new File(path);
       return file.exists();
   }

   /**
    * 获取本应用的数据存储路径
    * @return
    */
   public static String getFolderPath()
   {
       String pathString = mPath;
       isExist(pathString);
       pathString += "/";
       return pathString;
   }


   /**
    * 获取保存图片本地路径
    * @return
    */
   public static String getImgFolderPath()
   {
       String path = getFolderPath() + "image" ;
       isExist(path);
       path +="/";
       return path;
   }

   public static String getDownLoadPath(){
       String pathString = mPath;
       isExist(pathString);
       isExist(pathString);
       pathString = pathString+"/download";
       isExist(pathString);
       return pathString;
   }

   /**
    * 保存 JPG格式到SD卡中
    * @param bitmap 源bitmap
    * @param imageName 保存图片的名称
    * @param b_quality Hint to the compressor, 0-100. 0 meaning compress for small size, 100 meaning compress for max quality. Some formats, like PNG which is lossless, will ignore the quality setting
    */
   public static void saveJPGImageToSDCard(Bitmap bitmap, String imageName, int b_quality)
   {
       saveImageToSDCard(bitmap, imageName, b_quality, CompressFormat.JPEG);
   }

   /**
    * 保存 PNG格式到SD卡中
    * @param bitmap 源bitmap
    * @param imageName 保存图片的名称
    * @param b_quality Hint to the compressor, 0-100. 0 meaning compress for small size, 100 meaning compress for max quality. Some formats, like PNG which is lossless, will ignore the quality setting
    */
   public static void savePNGImageToSDCard(Bitmap bitmap, String imageName, int b_quality)
   {
       saveImageToSDCard(bitmap, imageName, b_quality, CompressFormat.PNG);
   }

   private static void saveImageToSDCard(Bitmap bitmap, String imageName, int b_quality, CompressFormat compressFormat)
   {
       String filePath = getImgFolderPath();
       int quality = 90;
       if(b_quality!=0){
           quality = b_quality;
       }
       FileOutputStream fos = null;
       File file = new File(filePath, imageName);
       try
       {
           fos = new FileOutputStream(file);
           if (null != fos)
           {
               bitmap.compress(compressFormat, quality, fos);
               fos.flush();
               fos.close();
           }
       }
       catch (FileNotFoundException e)
       {
           e.printStackTrace();
       }
       catch (IOException e)
       {
           e.printStackTrace();
       }
   }

   /**
    * 从程序本地文件夹中的image文件夹获取图像信息
    * @return Bitmap
    */
   public static Bitmap getImageFromSDCard(String imageName)
   {
       String filepath = getImgFolderPath() + imageName;
       File file = new File(filepath);
       if (file.exists())
       {
           Bitmap bm = BitmapFactory.decodeFile(filepath);
           return bm;
       }
       return null;
   }

   public static void saveFile(Context context, String filename, InputStream is)
   {
       BufferedInputStream bis = null;
       FileOutputStream fos = null;
       try
       {
           if (filename == null || is == null)
           {
               return;
           }
           bis = new BufferedInputStream(is, 1024);
           fos = new FileOutputStream(getFolderPath() + filename);
           byte[] buffer = new byte[1024];
           int length = -1;
           while ((length = bis.read(buffer)) != -1)
           {
               fos.write(buffer, 0, length);
           }
           fos.flush();
       }
       catch (Exception e)
       {
           e.printStackTrace();
       }
       finally
       {
           if (is != null)
           {
               try
               {
                   is.close();
               }
               catch (Exception e)
               {
               }
           }
           if (fos != null)
           {
               try
               {
                   fos.close();
               }
               catch (Exception e)
               {
               }
           }
           if (bis != null)
           {
               try
               {
                   bis.close();
               }
               catch (Exception e)
               {
               }
           }
       }
   }

   /**
    * 删除文件，不是删除文件夹，只需指定文件的名称，不需要整个路径
    * @param fileName 图片的名称
    */
   public static void deleteImageFile(String fileName)
   {
       File file = new File(getImgFolderPath() + fileName);
       if (file.exists())
       {
           file.delete();
       }
   }

   /**
    * 删除程序本地文件夹中的文件，只需指定文件名称。
    * @param fileName 如对应apk名称，对应软件包名称等等
    */
   public static void deleteFile(String fileName)
   {
       File file = new File(getFolderPath() + fileName);
       if (file.exists())
       {
           file.delete();
       }
   }

   /**
    * 删除整个程序本地文件夹
    * @param folder
    */
   public static boolean deleteDir(File folder)
   {
       if (folder == null || (!folder.exists()))
       {
           return false;
       }
       if (null != folder.listFiles())
       {
           for (File file : folder.listFiles())
               if (file.isDirectory())
               {
                   deleteDir(file);
               }
               else
               {
                   file.delete();
               }
       }
       return folder.delete();
   }

   /**
    * 图片重命名
    * @param oldName
    * @param newName
    */
   public static void renameForImage(String oldName, String newName)
   {
       String filePath = getImgFolderPath();
       File file = new File(filePath + oldName);
       file.renameTo(new File(filePath + newName));

   }

   /**
    * 按照参数条件进行bitmap的比例伸缩
    * @param bmap
    * @param w
    * @param h
    * @return
    */
   public static Bitmap scaleBitmap(Bitmap bmap, int w, int h)
   {
       if (bmap == null)
       {
           return null;
       }
       int width = bmap.getWidth();
       int height = bmap.getHeight();

       float scaleWidth = ((float) w / width);
       float scaleHeight = ((float) h / width);
       Matrix matrix = new Matrix();
       matrix.postScale(scaleWidth, scaleHeight);
       Bitmap newBm = Bitmap.createBitmap(bmap, 0, 0, width, height, matrix, true);
       return newBm;
   }

   public static void writeTOfileAndActiveClear(String filename, String msg)
   {
       writeToFile("LogData/", filename, msg, true);
   }

   public static void writeTOfile(String filename, String msg)
   {
       writeToFile("MapLogData/", filename, msg, false);
   }

   /**
    * 向文件写入G_sensor数据
    * @param filename
    * @param msg
    */
   public static void writeGsensorTOfile(String filename, String msg){
       writeToFile("Gsensor/", filename, msg, false);
   }

   /**
    * 向文件写入运动数据
    * @param filename
    * @param msg
    */
   public static void writeSportTOfile(String filename, String msg){
       writeToFile("SportData/", filename, msg, false);
   }

   public static void writeToFileInRoot(String filename, String msg)
   {
       writeToFile("LogData/", filename, msg, false);
   }

   private static void writeToFile(String middlePathName, String filename, String msg, boolean autoClear)
   {
       String path = getFolderPath();
       isExist(path);
       path = path + middlePathName;//"LogData/";
       isExist(path);
       File file = getFile(path , filename);
       try
       {
           if (!file.exists())
           {
               file.createNewFile();
           }
//			FileInputStream fis = new FileInputStream(file);
//			long size = fis.available();
//			fis.close();
//			/**
//			 * 当文件大小大于500MByte时，主动删除
//			 */
//			if (autoClear && size >= 500000000)
//			{
//				file.delete();
//				return;
//			}

           FileOutputStream stream = new FileOutputStream(file, true);
           String temp = msg + "\n";
           byte[] buf = temp.getBytes("utf-8");
           stream.write(buf);
           stream.close();

       }
       catch (IOException e)
       {
           // TODO Auto-generated catch block
           e.printStackTrace();
       }
   }

   /**
    * 奔溃日志文件
    * @param logFileName
    * @return
    */
   public static String getAPPLogFilePath(String logFileName){
       String path = getFolderPath();
       isExist(path);
       path = path+"LogData/";
       isExist(path);
       File file = new File(path + logFileName);
       if (!file.exists())
       {
           try {
               file.createNewFile();
           } catch (IOException e) {
               // TODO Auto-generated catch block
               e.printStackTrace();
           }
           return path + logFileName ;
       }
       FileInputStream fis = null ;
       try {
           fis = new FileInputStream(file);
           long size = fis.available();
           fis.close();
           /**
            * 当文件大小大于50MByte时，主动删除
            */
           if (size >= 50000000)
           {
               file.delete();
               file.createNewFile();
               return path + logFileName;
           }else{
               return path + logFileName;
           }
       } catch (Exception e) {
           // TODO: handle com.fenda.myutilslibrary.exception
       } finally
       {
           if (fis != null) {
               try {
                   fis.close();
               } catch (IOException e) {
                   // TODO Auto-generated catch block
                   e.printStackTrace();
               }
           }
       }
       return path + logFileName ;
   }
    public static String uriToPath(Context context, Uri uri) {
           if ("content".equalsIgnoreCase(uri.getScheme())) {
               String[] projection = { "_data" };
               Cursor cursor = null;

               try {
                   cursor = context.getContentResolver().query(uri, projection,null, null, null);
                   int column_index = cursor.getColumnIndexOrThrow("_data");
                   if (cursor.moveToFirst()) {
                       return cursor.getString(column_index);
                   }
               } catch (Exception e) {
                   // Eat it
               }
           }else if ("file".equalsIgnoreCase(uri.getScheme())) {
               return uri.getPath();
           }
           return null;
       }

   private static File getFile(String path , String filename) {
       File file = new File(path + filename);
       try {
           if (!file.exists()) {
               file.createNewFile();
           }
           FileInputStream fis = new FileInputStream(file);
           long size = fis.available();
           fis.close();
           /**
            * 当文件大小大于500MByte时，主动删除
            */
           if (size >= 500000000) {
               File f = new File(path + System.currentTimeMillis() + filename );
               file.renameTo(f);
           }
       } catch (IOException e) {
           // TODO Auto-generated catch block
           e.printStackTrace();
       }
       return new File(path + filename);
   }
}
